
package com.naza.rpc.netty;

import com.naza.rpc.model.RpcRequest;
import com.naza.rpc.model.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Rpc服务端消息处理
 * 
 * @author yl
 */
public class RpcReceiveHandler extends ChannelInboundHandlerAdapter {

    private final Map<String, Object> handlerMap;

    public RpcReceiveHandler(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }

    //收到客户端发来的请求,最顶层
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        RpcResponse response = new RpcResponse();
        //业务处理任务包装
        RecvInitializeTaskFacade facade = new RecvInitializeTaskFacade(request, response, handlerMap);
        Callable<Boolean> recvTask = facade.getTask();
        //不阻塞nio线程，复杂的业务逻辑丢给专门的线程池
        RpcReceiveExecutor.submit(recvTask, ctx, request, response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        //网络有异常关闭通道
        ctx.close();
    }
}

